package com.ctshk.rpc.iotc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ctshk.common.enums.OperationLogModel;
import com.ctshk.common.model.PageResponse;
import com.ctshk.rpc.iotc.dto.OperationLogDTO;
import com.ctshk.rpc.iotc.entity.OperateLogs;
import com.ctshk.rpc.iotc.mapper.OperateLogsMapper;
import com.ctshk.rpc.iotc.req.OperationLogsReq;
import com.ctshk.rpc.iotc.service.IOperateLogsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 操作日志表 服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-01-27
 */
@DubboService
public class OperateLogsServiceImpl extends ServiceImpl<OperateLogsMapper, OperateLogs> implements IOperateLogsService {

    @Autowired
    private OperateLogsMapper operateLogsMapper;

    @Override
    public PageResponse<OperationLogDTO> list(OperationLogsReq req) {
        QueryWrapper<OperateLogs> logQueryWrapper = new QueryWrapper<>();
        logQueryWrapper.eq("record_id",req.getId());
        logQueryWrapper.eq("model", OperationLogModel.IOTC.getModel());
        logQueryWrapper.orderByDesc("gmt_create");
        if(null != req.getLocalDateTime()){
            logQueryWrapper.like("gmt_create",req.getLocalDateTime());
        }
        if(null != req.getUserId()){
            logQueryWrapper.eq("user_id",req.getUserId());
        }
        List<OperateLogs> operationLogs = operateLogsMapper.selectList(logQueryWrapper);
        List<OperationLogDTO> operationLogDTOList = new ArrayList<>();
        for(int i = 0;i<operationLogs.size();i++){
            OperationLogDTO operationLogDTO = new OperationLogDTO();
            operationLogDTO.setUser(operationLogs.get(i).getUserId()+"");
            operationLogDTO.setLocalDateTime(operationLogs.get(i).getGmtCreate());
            operationLogDTO.setOperationType(operationLogs.get(i).getType());
            operationLogDTO.setOperationAfter(operationLogs.get(i).getResult());
            if( i != 0){
                operationLogDTO.setOperationBefore(operationLogs.get(i-1).getResult());
            }else {
                operationLogDTO.setOperationBefore(null);
            }
        }
        PageResponse<OperationLogDTO> operationLogDTOPageResponse = new PageResponse<>();
        operationLogDTOPageResponse.setRecords(operationLogDTOList);
        return operationLogDTOPageResponse;
    }
}
